// pages/medicalAdvice/medicalAdvice.js
var app = getApp();
Page({
  data: {
    // 病人信息
    patientName: '',
    genderOptions: ['男', '女', '其他'],
    genderIndex: 0,
    age: '',
    
    // 联系人信息
    contactName: '',
    contactPhone: '',
	phoneValid:false,
    verifyCode: '',
    showVerifyCode: false,
    isCountingDown: false,
    countdown: 0,
    
    // 病例信息
    medicalHistory: '',
    
    // 病例图片
    images: [],
    
    // 表单验证
    isFormValid: false,
	// 状态管理
	status: 'init', // init-初始 pending-等待中 replied-已回复
	adviceResult: null, // 医生回复结果
  },
onLoad() {
	const self= this
	wx.checkSession({
		success() { 
			console.log('succ')
			self.checkExistingRequest();
		},
		fail() { 
		  wx.login({
			success: (loginRes) => {
			  if (loginRes.code) {
				// 发送登录code到服务器获取session_key
				app.util.getUserInfo(function (response) {
					setTimeout(function(){
						self.checkExistingRequest();
					},500)
				});
			  }
			}
		  })
		}
	});
  },
  // 检查已有请求状态
    checkExistingRequest() {
      const requestId = wx.getStorageSync('lastAdviceRequestId');
      if (!requestId) return;
      const self = this
      wx.showLoading({ title: '检查状态中...' });
      // API调用检查状态
	  if(requestId){
		  app.util.request({
			url: 'Servicerecords/getAdviceData',
			data: {id:requestId},
			method:'GET',
			headers: {
				'Content-Type': 'application/json',
			},
			success(res) {
				if(res.data.code){					
					const mockResult = {
						status: res.data.data.status,
						data: {
						  diagnosis: res.data.data.diagnosis,
						  content: res.data.data.treatment,
						  replyTime: res.data.data.updatetime
						}
					}
					self.setData({
					  status: mockResult.status,
					  adviceResult: mockResult.status === 'replied' ? mockResult.data : null,
					  patientName:res.data.data.patient_name,
					  genderIndex:self.data.genderOptions.indexOf(res.data.data.patient_sex),
					  age:res.data.data.patient_age,
					  contactName:res.data.data.contect_name,
					  contactPhone:res.data.data.contect_phone,
					  medicalHistory:res.data.data.medical_history,
					  images:JSON.parse(res.data.data.attachments)
					});
				}else{
					wx.showToast({ title: '获取失败请重试' });
				}
			}
		  })
	  }
    },
  // 病人姓名变更
  onPatientNameChange(e) {
    this.setData({ patientName: e.detail.value });
    this.checkFormValidity();
  },

  // 性别选择
  onGenderChange(e) {
    this.setData({ genderIndex: e.detail.value });
    this.checkFormValidity();
  },

  // 年龄变更
  onAgeChange(e) {
    let age = e.detail.value;
    // 限制年龄范围1-120岁
    if (age > 120) age = 120;
    if (age < 1) age = '';
    
    this.setData({ age });
    this.checkFormValidity();
  },

  // 联系人姓名变更
  onContactNameChange(e) {
    this.setData({ contactName: e.detail.value });
    this.checkFormValidity();
  },

  // 手机号变更
  onPhoneChange(e) {
	this.setData({
	  contactPhone: e.detail.value,
	  phoneValid: this.validatePhoneNumber(e.detail.value) // 添加校验状态
	});
    this.checkFormValidity();
  },

// 校验手机号是否合法
  validatePhoneNumber(phone) {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  },
  // 验证码变更
  // onVerifyCodeChange(e) {
  //   this.setData({ verifyCode: e.detail.value });
  //   this.checkFormValidity();
  // },

  // 病例信息变更
  onMedicalHistoryChange(e) {
    this.setData({ medicalHistory: e.detail.value });
    this.checkFormValidity();
  },

  // 发送验证码
  // sendVerifyCode() {
  //   const { contactPhone } = this.data;
  //   if (!/^1[3-9]\d{9}$/.test(contactPhone)) {
  //     wx.showToast({ title: '请输入正确的手机号', icon: 'none' });
  //     return;
  //   }
    
  //   wx.showLoading({ title: '发送中...' });
  //   // 模拟API调用
  //   setTimeout(() => {
  //     wx.hideLoading();
  //     wx.showToast({ title: '验证码已发送' });
  //     this.startCountdown();
  //     this.setData({ showVerifyCode: true });
  //   }, 1000);
  // },

  // 开始倒计时
  // startCountdown() {
  //   this.setData({
  //     isCountingDown: true,
  //     countdown: 60
  //   });
    
  //   const timer = setInterval(() => {
  //     if (this.data.countdown <= 1) {
  //       clearInterval(timer);
  //       this.setData({
  //         isCountingDown: false,
  //         countdown: 0
  //       });
  //     } else {
  //       this.setData({ countdown: this.data.countdown - 1 });
  //     }
  //   }, 1000);
  // },

  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 3 - this.data.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // 检查图片大小
        const overSize = res.tempFiles.some(file => file.size > 5 * 1024 * 1024);
        if (overSize) {
          wx.showToast({ title: '图片不能超过5MB', icon: 'none' });
          return;
        }
        
        this.setData({
          images: [...this.data.images, ...res.tempFilePaths]
        });
      }
    });
  },

  // 删除图片
  removeImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.images.filter((_, i) => i !== index);
    this.setData({ images });
  },

  // 检查表单是否有效
  checkFormValidity() {
    const { 
      patientName, 
      age,
	  phoneValid,
      contactName, 
      contactPhone, 
      verifyCode, 
      showVerifyCode,
      medicalHistory
    } = this.data;
    
    const isValid = (
      patientName && 
      age &&
      contactName && 
      contactPhone && 
	  phoneValid &&
      // (!showVerifyCode || verifyCode) &&
      medicalHistory
    );
    
    this.setData({ isFormValid: isValid });
  },
	resetAdviceRequest(){
		this.setData({
			patientName:'',
			age:'',
			contactName:'',
			contactPhone:'',
			medicalHistory:'',
			images:[],
			status:'init'
		})
	},
  // 提交诊疗建议请求
  submitAdviceRequest() {
    if (!this.data.isFormValid) return;
    
    const {
      patientName, 
      genderIndex, 
      genderOptions, 
      age, 
      contactName, 
      contactPhone, 
      // verifyCode, 
      medicalHistory,
      images
    } = this.data;
    
    // 验证验证码（实际开发中应调用API验证）
    // if (this.data.showVerifyCode && !this.verifyCode) {
    //   wx.showToast({ title: '请输入验证码', icon: 'none' });
    //   return;
    // }
    
    var url = app.util.url('Common/upload');
    // 先上传图片（如果有）
    const uploadTasks = images.map(image => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: url,
          filePath: image,
          name: 'file',
          success: resolve,
          fail: reject
        });
      });
    });
    
    // 等待所有图片上传完成
    Promise.all(uploadTasks)
      .then(results => {
        const imageUrls = []
		results.map(function(res){
			imageUrls.push(JSON.parse(res.data).data.url)
		});
        // 构造请求数据
        const requestData = {
          patientInfo: {
            name: patientName,
            gender: genderOptions[genderIndex],
            age: parseInt(age)
          },
          contactInfo: {
            name: contactName,
            phone: contactPhone,
            // verifyCode
          },
          medicalHistory: medicalHistory,
		  status:'pending',
          images: imageUrls
        };
		let that = this
        let tempId=['rZMPQ_cuhcvMo6m8owotF1r-2kEBtOZlkR9p8vqXtUs','y6mNzqVmBt2GYZ6DK3SGh0AmJdgS9YGpWc81iyCcgSQ'];
        wx.requestSubscribeMessage({
          tmplIds: tempId,
          success (res) {
			  // 可以根据每个模板的订阅结果进行处理
				  tempId.forEach(templateId => {
					  console.log(res[templateId])
					if (res[templateId] === 'accept') {
					  console.log(`模板${templateId}订阅成功`)
					  // 可以记录用户已订阅的模板
					} else {
					  console.log(`模板${templateId}订阅失败或被拒绝`)
					  wx.showModal({
					  	title: '温馨提示',
					  	content: "您已关闭消息推送，如需要消息推送服务，请点击确定跳转设置页面打开授权后再次尝试。",
					  	success: function(modal) {
					  		if (modal.confirm) { // 点击确定
					  			wx.openSetting({ withSubscriptions: true })
					  		}
					  	}
					  })
					}
				  })
           },
           fail(err) { 
        			 console.log(err)
        			 if (err.errCode == '20004') {
        			  wx.showModal({
        				  title: '温馨提示',
        				  content: "您的消息订阅主已关闭，如需复习提醒服务，请点击确定跳转设置页面打开授权后再次尝试。",
        				  success: function(modal) {
        					  if (modal.confirm) { // 点击确定
        						  wx.openSetting({ withSubscriptions: true })
        					  }
        				  }
        			  })
        			}
        	},
        	complete(res) {
        	  console.log('complete  调用完成')
        	  // 无论取消还是接收都会执行:比如 下单(无论订阅号是取消还是接收都执行)
        		  
			  // 提交诊疗建议请求
			  return that.submitRequestToServer(requestData);
        	  
        	}
        })
      })
      .catch(err => {
        console.error('提交失败', err);
        wx.hideLoading();
        wx.showToast({ title: '提交失败', icon: 'none' });
      });
  },
   // 预览图片
    previewImage(e) {
      const url = e.currentTarget.dataset.url;
      wx.previewImage({
        current: url,
        urls: this.data.adviceResult.images
      });
    },
  // 提交到服务器
  submitRequestToServer(data) {
	  const self = this
	  return new Promise((resolve, reject) => {      
	  	  	        // 实际开发中应使用：
	  	  	  	  let jsonData = JSON.stringify(data);
	  	  	        app.util.request({
	  	  	        	url: 'Servicerecords/createData',
	  	  	        	data: jsonData,
	  	  	        	method:'POST',
	  	  	        	headers: {
	  	  	        		'Content-Type': 'application/json',
	  	  	        	},
	  	  	        	success(res) {
	  	  	        		console.log(res)
	  	  	        		if(res.data.code){
	  	  	        			wx.showToast({ title: '提交成功' });
	  							console.log(res.data.code)
	  							wx.setStorageSync('lastAdviceRequestId',res.data.data)
	  							self.setData({ status: 'pending' });
	  							setTimeout(() => {
	  							  wx.navigateBack();
	  							}, 1500);
	  	  	        		}else{
	  	  	        			wx.showToast({ title: '提交失败请重试' });
	  	  	        		}
	  	  	        	}
	  	  	        })
	  	  	      });
    
  }
});